<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 模板管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="success" @click="addEdit" v-has="2">新增模板</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                    v-has="2"
                >批量删除</el-button>
                                查询条件: 
                <el-input v-model="query.theme" placeholder="主题" class="handle-input mr10"></el-input>
                <el-input v-model="query.content" placeholder="内容" class="handle-input mr10"></el-input>
                <el-input v-model="query.fileName" placeholder="文件名" class="handle-input mr10"></el-input>
               <!-- <el-date-picker v-model="query.endTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" class="handle-input mr10"></el-date-picker>-->
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="" icon="el-icon-brush" @click="clearSearch">清空</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="tempId" label="ID" width="55" align="center"></el-table-column>
                <!--<el-table-column prop="operName" label="发布人名称"></el-table-column>-->
                <el-table-column prop="theme" label="主题"></el-table-column>
                <el-table-column prop="content" label="内容" align="center"></el-table-column>
                <el-table-column prop="fileName" label="资料模板文件" ></el-table-column>
                <el-table-column prop="endTime" label="截至时间" ></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                    	<el-button
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            v-has="2"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            size="mini"
                            icon="el-icon-upload2"
                            v-has="6"
                            @click="handleUpload(scope.$index, scope.row)"
                        >上传资料</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-download"
                            class="filter-item"
                            size="mini"
                            @click="downFileTemplate(scope.$index, scope.row)"
                        >下载模板</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="新增模板" :visible.sync="editVisible" width="40%" hight="50%">
            <el-form ref="form" :model="form" label-width="70px">
            	<el-form-item label="模板ID">
                    <el-input v-model="form.tempId" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="模板主题">
                    <el-input v-model="form.theme"></el-input>
                </el-form-item>
                <el-form-item label="模板内容">
                    <el-input v-model="form.content"></el-input>
                </el-form-item>
                <el-form-item label="截至时间">
					<el-col :span="11">
						<el-date-picker type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" v-model="form.endTime" style="width: 100%;"></el-date-picker>
					</el-col>
					<!--<el-col class="line" :span="2">-</el-col>
					<el-col :span="11">
						<el-time-picker placeholder="选择时间" v-model="form.endTime" style="width: 100%;"></el-time-picker>
					</el-col>-->
				</el-form-item>
                <el-form-item label="文件名">
                    <el-input v-model="form.fileName" :disabled="true">{{form.fileName}}</el-input>
                </el-form-item>
                <el-form-item label="文件路径">
                    <el-input v-model="form.filePath" :disabled="true">{{form.filePath}}</el-input>
                </el-form-item>
                <el-upload 
                	action=""
                	class="upload-demo"
                	drag
                	:limit="3"
	            	:http-request="uploadSectionFile">
	            <i class="el-icon-upload"></i>
	   			<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
	   			<div slot="tip" class="el-upload__tip">只能上传单个文件，多个文件请打包上传tar/zip，且不超过100MB</div>
	 			</el-upload>
           		<el-progress :text-inside="true" :stroke-width="18"
                       :percentage="uploadPercent"></el-progress>
                
            </el-form>
            
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit()">提交</el-button>
            </span>
        </el-dialog>
        
        <!-- 上传资料弹出框 -->
        <el-dialog title="上传资料" :visible.sync="editVisible1" width="40%" hight="50%">
            <el-form ref="form1" :model="form" label-width="70px">
            	<el-form-item label="模板ID">
                    <el-input v-model="form.tempId" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="模板主题">
                    <el-input v-model="form.theme" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="模板内容">
                    <el-input v-model="form.content" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="截至时间">
					<el-col :span="11">
						<el-date-picker type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" v-model="form.endTime"  :disabled="true" style="width: 100%;"></el-date-picker>
					</el-col>
					<!--<el-col class="line" :span="2">-</el-col>
					<el-col :span="11">
						<el-time-picker placeholder="选择时间" v-model="form.endTime" style="width: 100%;"></el-time-picker>
					</el-col>-->
				</el-form-item>
                <el-form-item label="文件名">
                    <el-input v-model="form.fileName2" :disabled="true">{{form.fileName2}}</el-input>
                </el-form-item>
                <el-form-item label="文件路径">
                    <el-input v-model="form.filePath2" :disabled="true">{{form.filePath2}}</el-input>
                </el-form-item>
                <el-upload 
                	action=""
                	class="upload-demo"
                	drag
                	:limit="3"
	            	:http-request="uploadMaterial">
	            <i class="el-icon-upload"></i>
	   			<!--<el-button size="small" type="primary">点击上传</el-button>-->
	   			<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
	   			<div slot="tip" class="el-upload__tip">只能上传单个文件，多个文件请打包上传tar/zip，且不超过100MB</div>
	 			</el-upload>
           		<el-progress :text-inside="true" :stroke-width="18"
                       :percentage="uploadPercent"></el-progress>
                
            </el-form>
            
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible1 = false">取消</el-button>
                <el-button type="primary" @click="commitMaterial()">提交</el-button>
            </span>
        </el-dialog>
        
    </div>
</template>

<script>
import {postRequest} from '../../utils/api'
import {uploadFileRequest} from '../../utils/api'
import axios from 'axios'
import Qs from 'qs'

export default {
    name: 'basetable',
    data() {
        return {
            query: {
                theme: '',
                content: '',
                fileName:'',
                endTime:'',
                pageIndex: 1,
                pageSize: 10
            },
            form:{},
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            editVisible1: false,
            pageTotal: 0,
            downloadPath:'E:/work/down/2222/',
            uploadPercent: 0,
            /*form: {},*/
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        async getData(){
	        let res = await this.$Http.getTemplateList(
	        	{
	        		pageNum:this.query.pageIndex,
	        		theme : this.query.theme,
	        		content : this.query.content
	        	},
                true
	        );
	        console.log(res.data);
	        //console.log(res.data.total);
	        this.tableData = res.data.list;
	        this.pageTotal = res.data.total || 10;
	    },
	    
	    //辅导员上传模板
	    uploadSectionFile(param) {
	    	let form = new FormData();
	    	var that = this;
	    	form.append('file', param.file);
	    	//form.append('dir', 'temp1')
	    	that.$axios.post('/template/upFileTemplateByManager.do', form, {
	    		headers: {
	    			'Content-Type': 'multipart/form-data'
	    		},
	    		onUploadProgress: progressEvent => {
	    			that.uploadPercent = (progressEvent.loaded / progressEvent.total * 100) | 0;
	    		}
	    	}).then((res) => {
	    		console.log('上传结束');
	    		console.log(res.data);
	    		//console.log(res.data.data.fileName);
	    		this.form.fileName = res.data.data.fileName;
	    		this.form.filePath = res.data.data.filePath;
	    		this.$set(this.form, 'fileName', res.data.data.fileName);
	    		this.$set(this.form, 'filePath', res.data.data.filePath);
	    		
	    	}).catch((err) => {
	    		console.log('上传错误')
	    		console.log(err)
	    	})
	    },
	    
	    //班级负责人下载模板
		downFileTemplate(index, row) {
		    let form = new FormData();
	    	var that = this;
	    	console.log('request:tempId='+ row.tempId +',fileName='+row.fileName + ',downloadPath=' + that.downloadPath);
	    	form.append('tempId', row.tempId);
	    	form.append('fileName', row.fileName);
	    	form.append('downloadPath', that.downloadPath);
	    	that.$axios.post('/template/downFileTemplateByClass.do', form, {
	    		responseType: 'blob',//声明后端返回的数据为二进制流

	    	}).then((res) => {
	    		console.log('下载结束');
	    		console.log(res);
	    		console.log(res.data);
	    		let blob = new Blob([res.data], { type: res.headers['content-type']})
				let downloadElement = document.createElement('a')
				let href = URL.createObjectURL(blob)
				//let href = res.data.data.url
				downloadElement.href = href
				//downloadElement.download = /*自定义文件名*/
				document.body.appendChild(downloadElement)
				downloadElement.click()
				document.body.removeChild(downloadElement)
				window.URL.revokeObjectURL(href)
	    		this.$message.success('下载成功');
	    	}).catch((err) => {
	    		console.log('下载错误:')
	    		console.log(err)
	    	})
		     
		},
		//上传共享资料
		uploadMaterial(param) {
	    	let form = new FormData();
	    	var that = this;
	    	form.append('upload_file', param.file);
	    	form.append('tempId', that.form.tempId);
	    	//form.append('fileName', param.fileName);
	    	//form.append('filePath', param.filePath);
	    	that.$axios.post('/template/uploadMaterialByClass.do', form, {
	    		headers: {
	    			'Content-Type': 'multipart/form-data'
	    		},
	    		onUploadProgress: progressEvent => {
	    			that.uploadPercent = (progressEvent.loaded / progressEvent.total * 100) | 0;
	    		}
	    	}).then((res) => {
	    		console.log('上传结束');
	    		console.log(res.data);
	    		//console.log(res.data.data.fileName);
	    		this.form.fileName2 = res.data.data.fileName;
	    		this.form.filePath2 = res.data.data.filePath;
	    		
	    	}).catch((err) => {
	    		console.log('上传错误')
	    		console.log(err)
	    	})
	    },
		
        // 触发搜索按钮
        async handleSearch() {
//          this.$set(this.query, 'pageIndex', 2);
//          this.getData();
	        let res = await this.$Http.getTemplateListByParams(
	        	{
	        		pageNum:this.query.pageIndex,
	        		theme : this.query.theme,
	        		content : this.query.content,
	        		fileName:this.query.fileName
	        	},
                true
	        );
	        console.log(res.data);
	        //console.log(res.data.total);
	        this.tableData = res.data.list;
	        this.pageTotal = res.data.total || 10;

        },
        //清空搜索栏
        clearSearch(){
        	this.query.theme = ''
        	this.query.content = ''
        	this.query.fileName = ''
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        async delAllSelection() {
            const length = this.multipleSelection.length;
            console.log('选择条数：'+length);
            if (length == 0) {this.$message.error(`请选择一条数据`);return;};
            let str = [];
            this.delList = this.delList.concat(this.multipleSelection);
            //console.log('选择信息：'+this.delList);
            for (let i = 0; i < length; i++) {
                str [i]= this.multipleSelection[i].tempId;
            }
            
            let res = await this.$Http.delTemplates(
	        	{
	        		ids : str
	        	},
	            true
	        );
            console.log(res);
	        if (res.status == 0){
	        	//this.$message.success(res.msg);
	        	this.delList = [];
	        }
            this.$message.success(res.msg);
            
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        //上传资料操作
        handleUpload(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible1 = true;
        },
        // 新增操作
        addEdit(){
            this.editVisible = true;
        },
        //编辑模板
        editTemp(){
        	const length = this.multipleSelection.length;
            console.log('选择编辑条数：'+length);
            if (length == 0 || length > 1) {this.$message.error(`请选中一条数据`);return;};
            this.editVisible = true;
        },
        // 提交模板
        async saveEdit() {
        	var _this = this;
        	if(_this.form.theme == undefined || _this.form.theme==''){
        		this.$message.error(`主题不能为空`);
        		return;
        	}
        	if(_this.form.content == undefined || _this.form.content==''){
        		this.$message.error(`内容不能为空`);
        		return;
        	}
        	if(_this.form.endTime == undefined || _this.form.endTime==''){
        		this.$message.error(`请选择截至时间`);
        		return;
        	}
        	if(_this.form.fileName == undefined || _this.form.fileName==''){
        		this.$message.error(`请上传文件再提交`);
        		return;
        	}
        	if(_this.form.filePath == undefined || _this.form.filePath==''){
        		this.$message.error(`请上传文件再提交`);
        		return;
        	}
        	
        	
            this.editVisible = false;
            console.log("tempId=" + _this.form.tempId);
            if (_this.form.tempId == undefined){
	            let formData = new FormData();
	        	formData.append("file",this.form.upload_file);
	       		let res = await this.$Http.saveOrUpdateTemplate(
		        	{
		        		theme : _this.form.theme,
		        		content : _this.form.content,
		        		fileName : _this.form.fileName,
		        		filePath : _this.form.filePath,
		        		endTime  : _this.form.endTime
		        	},
		            true
		        );
		        console.log(res);
		        if (res.status == 0){
		        	this.$message.success(`新增成功`);
		        	this.form = [];
		        }
	            this.$message.success(res.msg);
	            
	            this.$set(this.tableData, this.idx, this.form);
	        }else{
	        	let res = await this.$Http.saveOrUpdateTemplate(
		        	{
		        		tempId : _this.form.tempId,
		        		theme : _this.form.theme,
		        		content : _this.form.content,
		        		fileName : _this.form.fileName,
		        		filePath : _this.form.filePath,
		        		endTime  : _this.form.endTime
		        	},
		            true
		        );
		        console.log(res);
		        if (res.status == 0){
		        	this.$message.success(`编辑成功`);
		        	this.form = [];
		        }else{
	            	this.$message.success(res.msg);
	           }
	            //this.$set(this.tableData, this.idx, this.form);
	            this.getData();
	        }
            
        },
        
        //班级负责人提交上传资料
        async commitMaterial() {
            this.editVisible1 = false;
            var _this = this;
            console.log("commitMaterial_tempId=" + _this.form.tempId);
        	let res = await _this.$Http.commitMaterialByClass(
        		{
	        		tempId :   _this.form.tempId,
	        		fileName : _this.form.fileName2,
	        		filePath : _this.form.filePath2
	        	},
	            true
	        );
	        console.log(res);
	        if (res.status == 0){
	        	this.$message.success(`提交成功`);
	        	this.form = [];
	        }else{
            	this.$message.success(res.msg);
           }
            //this.$set(this.tableData, this.idx, this.form);
            this.getData();
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 200px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
